package com.ctg.itrdc.sysmgr.permission.core.control;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ctg.itrdc.sysmgr.permission.core.CtgToken;
import com.ctg.itrdc.sysmgr.permission.core.CtgUser;
import com.ctg.itrdc.sysmgr.permission.core.IPermissionService;
import com.ctg.itrdc.sysmgr.permission.core.dto.SystemPostDTO;
import com.ctg.itrdc.sysmgr.permission.core.utils.BeanPropertiesMapper;
import com.ctg.itrdc.sysmgr.permission.core.utils.CookieUtils;

@Controller
public class LoginController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public final static String REDIRECT = "redirect:";

	public final static String FORWARD = "forward:";
	@Resource
	private IPermissionService userService;

	/**
	 * 处理登录提交的方法
	 * 
	 * @param currUser
	 *            自动封装当前登录人的 账号,密码,验证码
	 * @param session
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	/**
	 * @api {post} /login 登录
	 * @apiGroup main
	 * @apiName loginPost
	 * @apiParam {String} sysUserCode
	 * @apiParam {String} password
	 * @apiParam {Long} sysPostId
	 * @apiParam {Boolean} rememberMe
	 * @apiVersion 0.0.1
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult loginPost(@RequestParam(required=false) String sysUserCode, @RequestParam(required=false) String password,
			@RequestParam(required = false) Long sysPostId, @RequestParam(required = false) Long rzOrgId,
			@RequestParam(defaultValue = "false") Boolean rememberMe, HttpServletResponse response) throws Exception {

		CommonResult result = new CommonResult();

		Subject subject = SecurityUtils.getSubject();
		// 通过账号和密码获取 UsernamePasswordToken token
		CtgToken token = new CtgToken(sysUserCode, password);
		token.setRememberMe(rememberMe);

		if (subject.isAuthenticated()) { // 第二次登录
			return loginWithSysPostId(sysPostId, rzOrgId, response, result, subject);
		}

		CommonResult checkResult = checkPermission(subject, token);
		if (checkResult != null) {
			return checkResult;
		}

		CtgUser shiroUser = (CtgUser) subject.getPrincipal();
		Long sysUserId = shiroUser.getSysUserId();

		// setCookie(response,SetCookieFilter.CTG_USER,
		// JSON.toJSONString(shiroUser));

		// 登录成功 更新登录次数
		userService.updateLoginNum(sysUserId);

		// 走authentication缓存
		List<Map<String,Object>> dtoList = userService.getPostByUId(sysUserId);
		// 如果只有一个岗位，则直接用该岗位登录
		if (dtoList != null && dtoList.size() == 1) {
			Map<String, Object> map = dtoList.get(0);
			Long postId = (Long) map.get("SYS_POST_ID");
			Map<String, Object> rzOrgIdMap = userService.getRzOrgIdByStaffId(shiroUser.getStaffId());
			rzOrgId = (Long) rzOrgIdMap.get("ORG_ID");
			return loginWithSysPostId(postId, rzOrgId, response, result, subject);
		}
		result.setData(BeanPropertiesMapper.mapList2DTOList(SystemPostDTO.class, dtoList));
		result.setResultCode(HttpStatus.OK.toString());
		return result;
	}

	private CommonResult loginWithSysPostId(Long sysPostId, Long rzOrgId, HttpServletResponse response,
			CommonResult result, Subject subject) {
		if (sysPostId == null && rzOrgId == null) {
			result.setResultCode(HttpStatus.OK.toString());
			result.setResultMsg("sysPostId,rzOrgId为空，不重新设置登录信息");
			return result;
		}
		// 查询post与user的关系。不存在关系抛异常
		CtgUser user = (CtgUser) subject.getPrincipal();
		if (sysPostId != null) {
			Long sysUserId = user.getSysUserId();
			if (!userService.existRelation(sysUserId, sysPostId)) { // 走sysPost缓存
				subject.logout();
				throw new AuthenticationException("岗位错误");
			}
			user.setSysPostId(sysPostId);
			List<String> roles = userService.getRoleCodes(sysUserId, sysPostId);

			if (roles != null && roles.size() > 0) {
				user.setSysRoles(roles.toArray(new String[roles.size()]));
			}
		}
		if (rzOrgId != null)
			user.setRzOrgId(rzOrgId);
		CookieUtils.setCookie(response, CookieUtils.CTG_USER, "{\"sysUserCode\":\""+user.getSysUserCode()+"\"}");
		result.setResultCode(HttpStatus.OK.toString());
		result.setResultMsg("登录成功");
		return result;
	}

	private CommonResult checkPermission(Subject user, CtgToken token) {
		CommonResult result = new CommonResult();
		try {
			user.login(token);
		} catch (UnknownAccountException uae) {
			result.setResultCode(HttpStatus.UNAUTHORIZED.toString());
			result.setResultMsg("账号不存在!");
			return result;
		} catch (IncorrectCredentialsException ice) {
			result.setResultCode(HttpStatus.UNAUTHORIZED.toString());
			result.setResultMsg("密码错误!");
			return result;
		} catch (LockedAccountException lae) {
			result.setResultCode(HttpStatus.LOCKED.toString());
			result.setResultMsg("账号被锁定!" + lae.getMessage());
			return result;
		} catch (Exception e) {
			logger.debug(e.getMessage());
			e.printStackTrace();
			result.setResultCode(HttpStatus.INTERNAL_SERVER_ERROR.toString());
			result.setResultMsg("未知错误,请联系管理员.");
			return result;
		}
		return null;
	}
	
}
